package com.platform.uaa.enhancer;

import com.google.common.collect.Maps;
import com.platform.comm.dto.DtoMapper;
import com.platform.comm.jwt.JwtTokenUtil;
import com.platform.comm.util.DateTimeUtil;
import com.platform.uaa.service.CustomUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.stream.Collectors;


/**
 * JWT内容增强器
 *
 * @author zyk
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {

  @Autowired
  private DtoMapper dtoMapper;

  @Override
  public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal();
    JwtTokenUtil.JwtUser jwtUser = dtoMapper.map(userDetails, JwtTokenUtil.JwtUser.class);
    jwtUser.setPwdExpire(DateTimeUtil.toStdLongTimeStr(userDetails.getLastPasswordReset()));
    jwtUser.setDepartKind(userDetails.getDepartKind());
    jwtUser.setDepartId(userDetails.getDepartId());
    jwtUser.setDepartName(userDetails.getDepartName());
    jwtUser.setAdmin(userDetails.isAdmin());
    jwtUser.setFirst(userDetails.isFirst());
    jwtUser.setAuth(userDetails.getAuthorities()
            .parallelStream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.joining(",")));
    Map<String, Object> claims = Maps.newHashMap();
    claims.put(JwtTokenUtil.CLAIM_KEY_USER, jwtUser);
    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(claims);
    return accessToken;
  }

}
